//
//  userContentController.m
//  pacc
//
//  Created by 测试 on 2018/5/24.
//  Copyright © 2018年 测试. All rights reserved.
//

#import "userContentController.h"
#import <AFNetworking.h>
#import "ZXNavigationController.h"
#import "updatenameController.h"
@interface userContentController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>{
    AFHTTPSessionManager *manager;

    UIImagePickerController *pickerController;
}
@property (weak, nonatomic) IBOutlet UIImageView *headIcon;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@end

@implementation userContentController
- (IBAction)choseImg:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"选择头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
    [actionSheet showInView:[UIApplication sharedApplication].keyWindow];
}
- (IBAction)updateName:(id)sender {
    self.title = @"更改名字";
    updatenameController *vc = [updatenameController new];
    vc.nickName = _userNameLabel.text;
    vc.userDesc = _userDesc;
    vc.returnnameBlock = ^(NSString *name) {
        _userNameLabel.text = name;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initHeadIcon];
    //初始化pickController
    [self createData];
    _userNameLabel.text = _userName;
    self.view.backgroundColor =baseBackgroundColor;
}
-(void)viewWillAppear:(BOOL)animated{
    //初始化头像控件
    NSString *path_document = NSHomeDirectory();
    NSString *imagePath = [path_document stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@.png",my_AppDelegate.userid]];
    NSLog(@"imagePath==%@",imagePath);
    UIImage *getimage2 = [UIImage imageWithContentsOfFile:imagePath];
    self.title = @"";
    [_headIcon setImage:getimage2];
}

- (void)initHeadIcon
{
    
    self.headIcon.layer.cornerRadius = self.headIcon.frame.size.height/2;
    self.headIcon.clipsToBounds = YES;
    self.headIcon.layer.borderColor = [UIColor whiteColor].CGColor;
    self.headIcon.layer.borderWidth = 3;
}
- (void)createData
{
    //初始化pickerController
    pickerController = [[UIImagePickerController alloc]init];
    pickerController.view.backgroundColor = baseBackgroundColor;
    pickerController.view.backgroundColor = baseBlueColor;
    pickerController.delegate = self;
    pickerController.allowsEditing = YES;
    if ([pickerController.navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
        [pickerController.navigationBar setBarTintColor:baseBlueColor];
        [pickerController.navigationBar setTranslucent:YES];
        [pickerController.navigationBar setTintColor:baseBlueColor];
    }else{
        [pickerController.navigationBar setBackgroundColor:[UIColor colorWithWhite:0.1 alpha:1.0]];
    }
    //    更改titieview的字体颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
    [pickerController.navigationBar setTitleTextAttributes:attrs];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {//相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            NSLog(@"支持相机");
            [self makePhoto];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil];
            [alert show];
        }
    }else if (buttonIndex == 1){//相片
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            NSLog(@"支持相册");
            [self choosePicture];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->照片，中开启本应用的相机访问权限！！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil];
            [alert show];
        }
    }else if (buttonIndex == 2){//图册
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
        {
            NSLog(@"支持图库");
            [self pictureLibrary];
            //            [self presentViewController:picker animated:YES completion:nil];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->照片，中开启本应用的相机访问权限！！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil];
            [alert show];
        }
    }else if (buttonIndex == 3){
        
    }
    
}
//跳转到imagePicker里
- (void)makePhoto
{
    pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    pickerController.navigationController.navigationBar.barTintColor = baseBlueColor;
    [self presentViewController:pickerController animated:YES completion:nil];
}
//跳转到相册
- (void)choosePicture
{
    pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    
    [self presentViewController:pickerController animated:YES completion:nil];
}
//跳转图库
- (void)pictureLibrary
{
    pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:pickerController animated:YES completion:nil];
}
//用户取消退出picker时候调用
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"%@",picker);
    [pickerController dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//用户选中图片之后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    NSLog(@"%s,info == %@",__func__,info);
    
    UIImage *userImage = [self fixOrientation:[info objectForKey:@"UIImagePickerControllerOriginalImage"]];
    
    userImage = [self scaleImage:userImage toScale:0.3];
    NSData *data = UIImageJPEGRepresentation(userImage, 0.1);
    NSLog(@"当前大小%fkb",(float)[data length]/1024.0f);
    UIImage *resultImage = [UIImage imageWithData:data];
    UIImage *uploadImage = [UIImage scaleImage:resultImage toKb:500];
    //保存图片
    [pickerController dismissViewControllerAnimated:YES completion:^{

    }];
    //照片上传
    [NetWorking upDateHeadIcon:resultImage parameters:nil imageName:@"headImage" success:^(NSDictionary *data) {
        NSString *status =[NSString stringWithFormat:@"%@", [data objectForKey:@"status"]];
        if ([status isEqualToString:@"200"]) {
            [self.headIcon setImage:userImage];
            self.headIcon.contentMode = UIViewContentModeScaleAspectFill;
            self.headIcon.clipsToBounds = YES;
            NSDictionary *dic = [data objectForKey:@"data"];
            NSString *url = [dic objectForKey:@"url"];
            [NetWorking startPOSTRequestWithUrl2:[NSString stringWithFormat:@"userputHead"] parameters:@{@"token":my_AppDelegate.token,@"url":url} logMes:@"上传头像url" success:^(NSDictionary *data) {
                NSString *status = [NSString stringWithFormat:@"%@",[data objectForKey:@"status"]];
                    if ([status isEqualToString:@"200"]) {
                        //拿到图片
                        NSString *path_document = NSHomeDirectory();
                        //设置一个图片的存储路径
                        NSString *imagePath = [path_document stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@.png",my_AppDelegate.userid]];
                        //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
                        [UIImagePNGRepresentation(userImage) writeToFile:imagePath atomically:YES];
                        self->_returnValueBlock(userImage);
                        NSString *msg = [NSString stringWithFormat:@"%@",[dic objectForKey:@"msg"]];
                        [SVProgressHUD showWithStatus:msg];
                        [SVProgressHUD setBackgroundColor:RGB(85, 85, 85)];
                        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];;
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        });
                    }else{
                        NSString *msg = [NSString stringWithFormat:@"%@",[dic objectForKey:@"msg"]];
                        [SVProgressHUD showErrorWithStatus:msg];
                        [SVProgressHUD setBackgroundColor:RGB(85, 85, 85)];
                        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];;
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        });
                    }
                
            } failure:^(NSError *error) {
                
            }];
            
        }
        NSLog(@"upload%@",data);
    } failure:^(NSError *error) {
        
    }];
}
+ (NSString *)parseParams:(NSDictionary *)params
{
    NSString *keyValueFormat;
    NSMutableString *result = [NSMutableString new];
    NSMutableArray *array = [NSMutableArray new];
    //实例化一个key枚举器用来存放dictionary的key
    NSEnumerator *keyEnum = [params keyEnumerator];
    id key;
    while (key = [keyEnum nextObject]) {
        keyValueFormat = [NSString stringWithFormat:@"%@=%@&", key, [params valueForKey:key]];
        [result appendString:keyValueFormat];
        [array addObject:keyValueFormat];
    }
    return result;
}
//保存照片到沙盒路径(保存)
- (void)saveImage:(UIImage *)image name:(NSString *)iconName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    //写入文件
    NSString *icomImage = my_AppDelegate.userid;
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", icomImage]];
    // 保存文件的名称
    //    [[self getDataByImage:image] writeToFile:filePath atomically:YES];
    [UIImagePNGRepresentation(image)writeToFile: filePath  atomically:YES];
}
//缩放图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"%@",NSStringFromCGSize(scaledImage.size));
    return scaledImage;
}
//修正照片方向(手机转90度方向拍照)
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
